'use client'
import React, { useEffect, useState, useMemo } from "react";
import { Table, Input, Button, message, Tag, Popconfirm } from "antd";
import type { ColumnsType } from "antd/es/table";
import './index.scss'
import { getJson, writeDocument } from '@/app/api/index'
import { LabelItem, ConfigType } from '../type'
import ModalUi from "./ModalUi/page";
import { PositionName } from '../tool'


const ManageTable: React.FC = ({ }) => {
    const [file] = useState("config.json");
    const [search, setSearch] = useState("");
    const [config, setConfig] = useState<ConfigType>({
        Config_Trigger: [],
        Config_Label: [],
        Config_Default: ''
    });
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [data, setData] = useState({})
    const [type, settype] = useState<any>('')


    useEffect(() => {
        getlist()
    }, [isModalOpen]);

    const getlist = async () => {
        const data = await getJson();
        setConfig(data.data);
    }

    const filterTableData = useMemo(
        () =>
            config.Config_Label.filter(
                (data) =>
                    !search || data.name.toLowerCase().includes(search.toLowerCase())
            ),
        [config.Config_Label, search]
    );

    const save = async (item: any, type: string) => {
        let data: any;
        if (type === "delete") data = await writeDocument(file, item, "delete");
        if (type === "Trigger") data = await writeDocument(file, config.Config_Trigger.filter((item) => item !== ""), "Trigger")
        if (data.code === 200) message.success(data.msg);
        else message.error(data.msg);
        getlist();
    };

    const wordAdd = () => {
        if (config.Config_Trigger.findIndex((item) => item === "") === -1)
            setConfig((prev) => ({
                ...prev,
                Config_Trigger: [...prev.Config_Trigger, ""],
            }));
        else message.error("请填写唤醒词");
    };

    const columns: ColumnsType<LabelItem> = [
        { title: "栏目名", dataIndex: "name", key: "name", width: 130 },
        { title: "地址", dataIndex: "url", key: "url", width: 130 },
        {
            title: '位置', dataIndex: 'position', key: 'position', width: 130,
            render: (item, record) => {
                return <Tag color="default">{PositionName(item)}</Tag>
            }
        },
        {
            title: <Input placeholder="搜索标签名" value={search} onChange={(e) => setSearch(e.target.value)} />,
            key: "search",
            align: "right",
            width: 150
        },
        {
            key: "action",
            fixed: 'right',
            width: 150,
            render: (_, record) => <div className="table_btn">
                <a onClick={() => {
                    setIsModalOpen(true)
                    settype('edit')
                    setData(record)
                }}>修改</a>
                <Popconfirm
                    title="确定删除吗"
                    description="删除后将无法恢复"
                    onConfirm={() => { save(record, "delete") }}
                    okText="确认"
                    cancelText="取消"
                >
                    <a >删除</a>
                </Popconfirm>
            </div>
        },
    ];

    return (
        <div className="manage_table">
            <div className="table_content">
                <div className="label">栏目集讲解词</div>
                <Table
                    dataSource={filterTableData}
                    columns={columns}
                    pagination={false}
                    className="tabledata"
                    style={{ width: "100%" }}
                    scroll={{ y: 430 }}
                />
                <Button onClick={() => {
                    setData({})
                    settype('add')
                    setIsModalOpen(true)
                }}>添加</Button>
            </div>
            <div className="trigger">
                <div className="label">数字人唤醒词</div>
                <div className="trigger_item">
                    {config.Config_Trigger.map((item, index) => (
                        <Input
                            key={index}
                            placeholder="请输入唤醒词"
                            value={item}
                            onChange={(e) => {
                                const newArr = [...config.Config_Trigger];
                                newArr[index] = e.target.value;
                                setConfig((prev) => ({ ...prev, Config_Trigger: newArr }));
                            }}
                            allowClear
                            style={{ width: '30%', margin: '1.5%' }}
                        />
                    ))}
                </div>
                <div className="word_btn">
                    <Button onClick={wordAdd}>添加</Button>
                    <Button onClick={() => save("", "Trigger")} style={{ marginLeft: 8 }}>保存</Button>
                </div>
            </div>

            <ModalUi form_data={data} type={type} isopen={isModalOpen} setdata={(value) => setIsModalOpen(value)} />
        </div>
    )
}

export default ManageTable